//
// Created by Administrator on 2021/10/21.
//

#include "Scene.h"
/**
 * 场景当前激活相机
 */
static Camera * activeCamera;

Scene::Scene() {
    type = GET_CLASS(__FILE__);
    name = type + "_" + id;
}

Camera *Scene::getActiveCamera() const {
    return activeCamera;
}

void Scene::setActiveCamera(Camera * _currCamera) {
    if(!childrenList.empty()) {
        for (auto iterator = childrenList.begin(); iterator != childrenList.end(); ++iterator) {
            Camera * camera = dynamic_cast<Camera *>(*iterator);
            if(camera == _currCamera){
                log_info("Set main camera success, %s", camera->name.c_str());
                activeCamera = camera;
                return;
            }
        }
    }
    MAssert::check(false, "相机未添加到场景中，无法激活！");
}

Scene::~Scene() {
    log_info("gc Scene! %p", this);
    if(!childrenList.empty()) {
        for (auto iterator = childrenList.begin(); iterator != childrenList.end(); ++iterator) {
            if (NULL != *iterator) {
                SAFE_DELETE(*iterator);
            }
        }
        std::vector<Object3D*>().swap(childrenList);
    }
    activeCamera = NULL;
}

void Scene::onInit() {
    MAssert::check(!childrenList.empty(), "场景列表为空");
    for (auto iterator = childrenList.begin(); iterator != childrenList.end(); ++iterator) {
        Object3D* it = *iterator;
        it->onInit();
    }
}

void Scene::onRender(float time, Matrix4x4 proj, Matrix4x4 view, Matrix4x4 pworld) {

}

/**
* 场景中添加物体
* @param object 物体，继承自Object3D
*/
void Scene::add(Object3D* object) {
    MAssert::check(object);
    log_info("Scene add : %s", object->name.c_str());
    MAssert::check(this != object, "不允许添加自己进场景");

    childrenList.push_back(object);
}

/**
 * 移除并销毁
 * @param object
 */
void Scene::remove(Object3D *object) {
    log_info("scene remove : %s", object->name.c_str());
    MAssert::check(!childrenList.empty(), "场景列表为空");

    for (auto iterator = childrenList.begin(); iterator != childrenList.end(); ++iterator) {
        if(*iterator == object){
            childrenList.erase(iterator);
        }
    }
}

/**
 * 提供外部查看
 * @return 子列表
 */
const std::vector<Object3D *> &Scene::getChildrenList() const {
    return childrenList;
}

/**
 * 静态方法提供给外部，可能为空
 * @return 场景中正处于激活中的相机
 */
Camera *Scene::getStaticActiveCamera() {
    return activeCamera;
}














